package com.putong35.common.utils;


import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Proxy;
import android.os.Build;


/**
 * 网络工具
 *
 * @Author: PV
 * @E-mail: pengveivei@sina.cn
 * @CreateDate: 2016-6-20
 * @Version: 1.0.0
 */
public class NetUtil {

	public static final int NETWORK_STATE_IDLE = -1;
	public static final int NETWORK_STATE_WIFI = 1;
	public static final int NETWORK_STATE_CMNET = 2;
	public static final int NETWORK_STATE_CMWAP = 3;
	public static final int NETWORK_STATE_CTWAP = 4;


	/**
	 * 返回网络状态
	 * 
	 * @return 1为成功WiFi已连接，2为cmnet，3为cmwap，4为ctwap， -1为网络未连接
	 */
	public static int getNetworkStatus(Context context) {
		ConnectivityManager mConnectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);// 上下文连接服务
		NetworkInfo info = mConnectivity.getActiveNetworkInfo();// 给定网络接口的状态类型
		if (info == null || !info.isAvailable()) {// 无网络判断
			return NETWORK_STATE_IDLE;
		}
		String typeName = info.getTypeName();
		if (typeName.equals("WIFI")) {
			return NETWORK_STATE_WIFI;
		}
		String extraName = info.getExtraInfo();
		if (extraName == null || extraName.trim().length() == 0) {
			String proxyHost = null;
			if (Build.VERSION.SDK_INT >= 13) {
				proxyHost = System.getProperties().getProperty("http.proxyHost");
			} else {
				proxyHost = Proxy.getHost(context);
			}
			return (proxyHost == null ? NETWORK_STATE_CMNET : NETWORK_STATE_CMWAP);
		}

		if (extraName.equals("cmnet") || extraName.equals("3gnet") || extraName.equals("uninet")
				|| extraName.equals("ctnet") || extraName.equals("ctnet:CDMA") || extraName.equals("CTC")) {
			return NETWORK_STATE_CMNET;
		} else if (extraName.equals("cmwap") || extraName.equals("3gwap") || extraName.equals("uniwap")) {
			return NETWORK_STATE_CMWAP;
		} else if ("ctwap:CDMA".equals(extraName) || extraName.equals("ctwap") || extraName.equals("#777")) {
			return NETWORK_STATE_CTWAP;
		}

		String proxyHost = null;
		if (Build.VERSION.SDK_INT >= 13) {
			proxyHost = System.getProperties().getProperty("http.proxyHost");
		} else {
			proxyHost = Proxy.getHost(context);
		}
		return (proxyHost == null ? NETWORK_STATE_CMNET : NETWORK_STATE_CMWAP);
	}


	/**
	 * 判断网络是否可用
	 * @param context
	 * @return
     */
	public static boolean isAvalible(Context context) {
		return getNetworkStatus(context) != NETWORK_STATE_IDLE;
	}

}
